<template>
  <div class="page-container">
    <div class="background-animation"></div>
    
    <div class="retrieve-password">
      <h2 class="title">
        <span class="title-text">KKUsed Book找回密码</span>
        <div class="title-underline"></div>
      </h2>

      <el-card class="password-card">
        <el-steps :active="activeStep" finish-status="success" align-center class="custom-steps">
          <el-step title="身份验证" :icon="User"></el-step>
          <el-step title="密码重置" :icon="Lock"></el-step>
          <el-step title="重置完成" :icon="CircleCheckFilled"></el-step>
        </el-steps>

        <div class="step-content">
          <!-- 步骤1：身份验证 -->
          <div v-if="activeStep === 1" class="form-container animate__animated animate__fadeIn">
            <el-form 
              ref="verifyFormRef" 
              :model="verifyForm" 
              :rules="verifyRules" 
              label-width="0"
            >
              <el-form-item prop="email" class="custom-form-item">
                <el-input 
                  v-model="verifyForm.email" 
                  placeholder="请输入邮箱" 
                  :prefix-icon="Message"
                  class="custom-input"
                />
              </el-form-item>

              <el-form-item prop="code" class="custom-form-item">
                <el-input 
                  v-model="verifyForm.code" 
                  placeholder="请输入验证码" 
                  class="verify-input custom-input"
                >
                  <template #prefix>
                    <el-icon><Promotion /></el-icon>
                  </template>
                  <template #append>
                    <el-button 
                      class="verify-btn"
                      :loading="loading"
                      :disabled="cooldown > 0 || loading" 
                      @click="sendVerifyCode"
                    >
                      {{ cooldown > 0 ? `${cooldown}s后重试` : '获取验证码' }}
                    </el-button>
                  </template>
                </el-input>
              </el-form-item>
            </el-form>
          </div>

          <!-- 步骤2：密码重置 -->
          <div v-if="activeStep === 2" class="form-container animate__animated animate__fadeIn">
            <el-form 
              ref="passwordFormRef" 
              :model="passwordForm" 
              :rules="passwordRules" 
              label-width="0"
            >
              <el-form-item prop="password" class="custom-form-item">
                <el-input 
                  v-model="passwordForm.password" 
                  type="password" 
                  placeholder="新密码" 
                  :prefix-icon="Lock" 
                  show-password
                  class="custom-input"
                />
              </el-form-item>

              <el-form-item prop="confirmPassword" class="custom-form-item">
                <el-input
                  v-model="passwordForm.confirmPassword"
                  type="password"
                  placeholder="确认新密码"
                  :prefix-icon="Lock"
                  show-password
                  class="custom-input"
                />
              </el-form-item>
            </el-form>
          </div>

          <!-- 步骤3：重置完成 -->
          <div v-if="activeStep === 3" class="success-container animate__animated animate__bounceIn">
            <div class="success-icon-wrapper">
              <el-icon class="success-icon" color="#67C23A"><CircleCheckFilled /></el-icon>
            </div>
            <h3>密码重置成功</h3>
            <p>请使用新密码登录您的账户</p>
          </div>

          <!-- 底部按钮 -->
          <div class="button-group">
            <el-button 
              v-if="activeStep > 1" 
              @click="prevStep"
              class="custom-button secondary-button"
            >
              上一步
            </el-button>
            <el-button 
              type="primary" 
              v-if="activeStep < 3" 
              @click="nextStep"
              class="custom-button primary-button"
            >
              下一步
            </el-button>
            <el-button 
              type="primary" 
              v-if="activeStep === 3" 
              @click="goToLogin"
              class="custom-button primary-button"
            >
              返回登录
            </el-button>
          </div>
        </div>
      </el-card>
    </div>
  </div>
</template>
<script setup lang="ts">
import { ElMessage } from 'element-plus'
import { Message, Lock, CircleCheckFilled, Promotion, User } from '@element-plus/icons-vue'
import { reactive, ref } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import router from '@/router';
import type { ResponseData } from '@/types';
import { http } from '@/services/http';

interface VerifyFormState {
  email: string
  code: string
}

interface PasswordFormState {
  password: string
  confirmPassword: string
}

// 当前步骤
const activeStep = ref(1)

// 验证表单
const verifyForm = reactive<VerifyFormState>({
  email: '',
  code: '',
})

// 密码表单
const passwordForm = reactive<PasswordFormState>({
  password: '',
  confirmPassword: '',
})

// 表单refs
const verifyFormRef = ref<FormInstance>()
const passwordFormRef = ref<FormInstance>()

// 验证邮箱格式
const validateEmail = (rule: any, value: string, callback: any) => {
  const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
  if (!value) {
    callback(new Error('请输入邮箱'))
  } else if (!emailRegex.test(value)) {
    callback(new Error('请输入正确的邮箱格式'))
  } else {
    callback()
  }
}

// 验证规则
const verifyRules = reactive<FormRules>({
  code: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    { min: 6, max: 6, message: '验证码长度应为6位', trigger: 'blur' }
  ],
  email: [
    { required: true, validator: validateEmail, trigger: 'blur' }
  ],
})

const passwordRules = reactive<FormRules>({
  password: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能小于6位', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认新密码', trigger: 'blur' },
    {
      validator: (rule: any, value: string, callback: any) => {
        if (value !== passwordForm.password) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
})

// 验证码倒计时
const cooldown = ref(0)

// 发送验证码
const loading = ref(false)

const sendVerifyCode = async () => {
  // 防止重复点击
  if (cooldown.value > 0 || loading.value) return
  
  try {
    loading.value = true
    
    // 验证邮箱格式
    await verifyFormRef.value?.validateField('email')
    
    // 发送验证码请求
    const res = await http.get<ResponseData>('/email/code', { email: verifyForm.email })
    
    if (res.flag) {
      // 发送成功，开始倒计时
      cooldown.value = 60
      const timer = setInterval(() => {
        cooldown.value--
        if (cooldown.value <= 0) {
          clearInterval(timer)
        }
      }, 1000)
      
      ElMessage.success('验证码已发送至您的邮箱')
    } else {
      ElMessage.error(res.msg || '验证码发送失败')
    }
  } catch (error: any) {
    ElMessage.error(error.response?.data?.message || '发送失败，请检查邮箱格式或网络连接')
  } finally {
    loading.value = false
  }
}

// 下一步
const nextStep = async () => {
  if (activeStep.value === 1) {
    try {
      await verifyFormRef.value?.validate()
      const res = await http.post<ResponseData>('/verify',verifyForm)
      console.log(111,res);
      
      if(res.flag){
        activeStep.value++
      }else{
        ElMessage({type:'warning',message:res.msg})
      }
     
    } catch (error) {
      return
    }
  } else if (activeStep.value === 2) {
    try {
      await passwordFormRef.value?.validate()
      const param={
        newPwd:passwordForm.password,
        email:verifyForm.email
      }
      const res =await http.post<ResponseData>('/findPwd',param)
      if(res.flag){
        ElMessage({type:"success",message:res.msg})
        activeStep.value++
      }
    } catch (error) {
      return
    }
  }
}

// 上一步
const prevStep = () => {
  if (activeStep.value > 1) {
    activeStep.value--
  }
}

// 返回登录
const goToLogin = () => {
  ElMessage.success('即将返回登录页面')
  router.push({ name: 'login' });
}
</script>

<style scoped>
.page-container {
  min-height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  background: linear-gradient(135deg, #1a1a1a 0%, #373737 100%);
  position: relative;
  overflow: hidden;
}

.background-animation {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: 
    radial-gradient(circle at 10% 20%, rgba(91, 37, 195, 0.1) 0%, transparent 40%),
    radial-gradient(circle at 90% 80%, rgba(37, 195, 164, 0.1) 0%, transparent 40%);
  animation: backgroundMove 15s ease infinite;
  z-index: 1;
}

@keyframes backgroundMove {
  0% { transform: scale(1); }
  50% { transform: scale(1.1); }
  100% { transform: scale(1); }
}

.retrieve-password {
  width: 100%;
  max-width: 600px;
  margin: 40px;
  position: relative;
  z-index: 2;
}

.title {
  text-align: center;
  margin-bottom: 40px;
  position: relative;
}

.title-text {
  color: #fff;
  font-size: 32px;
  font-weight: 600;
  letter-spacing: 2px;
  text-shadow: 0 2px 4px rgba(0,0,0,0.2);
}

.title-underline {
  width: 60px;
  height: 3px;
  background: linear-gradient(90deg, #409EFF, #67C23A);
  margin: 15px auto 0;
  border-radius: 2px;
}

.password-card {
  padding: 40px;
  border-radius: 16px;
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  transition: transform 0.3s ease;
}

.password-card:hover {
  transform: translateY(-5px);
}

.custom-steps {
  margin-bottom: 50px;
}

:deep(.el-steps) {
  --el-step-icon-size: 34px;
}

:deep(.el-step__icon.is-text) {
  border-radius: 50%;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.form-container {
  max-width: 400px;
  margin: 0 auto;
}

.custom-form-item {
  margin-bottom: 25px;
}

.custom-input :deep(.el-input__wrapper) {
  border-radius: 8px;
  padding: 12px;
  transition: all 0.3s ease;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
}

.custom-input :deep(.el-input__wrapper:hover) {
  box-shadow: 0 4px 16px rgba(64, 158, 255, 0.1);
}

.verify-btn {
  padding: 12px 20px;
  border: none;
  background: linear-gradient(90deg, #409EFF, #67C23A);
  color: white;
  transition: all 0.3s ease;
}

.verify-btn:not(:disabled):hover {
  opacity: 0.9;
  transform: translateY(-1px);
}

.success-container {
  text-align: center;
  padding: 40px 0;
}

.success-icon-wrapper {
  width: 80px;
  height: 80px;
  margin: 0 auto 20px;
  background: rgba(103, 194, 58, 0.1);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.success-icon {
  font-size: 40px;
  animation: iconPop 0.5s ease;
}

@keyframes iconPop {
  0% { transform: scale(0); }
  50% { transform: scale(1.2); }
  100% { transform: scale(1); }
}

.button-group {
  margin-top: 40px;
  display: flex;
  justify-content: center;
  gap: 16px;
}

.custom-button {
  padding: 12px 30px;
  border-radius: 8px;
  font-weight: 500;
  transition: all 0.3s ease;
}

.primary-button {
  background: linear-gradient(90deg, #409EFF, #67C23A);
  border: none;
}

.primary-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);
}

.secondary-button {
  border: 2px solid #409EFF;
  color: #409EFF;
  background: transparent;
}

.secondary-button:hover {
  background: rgba(64, 158, 255, 0.1);
}

/* 添加响应式样式 */
@media (max-width: 768px) {
  .retrieve-password {
    margin: 20px;
  }

  .password-card {
    padding: 20px;
  }

  .title-text {
    font-size: 24px;
  }
}

/* 添加动画类 */
.animate__animated {
  animation-duration: 0.5s;
}

@keyframes fadeIn {
  from { opacity: 0; }
  to { opacity: 1; }
}

@keyframes bounceIn {
  0% { transform: scale(0.3); opacity: 0; }
  50% { transform: scale(1.05); }
  70% { transform: scale(0.9); }
  100% { transform: scale(1); opacity: 1; }
}

@keyframes hue-rotate {
  from {
    filter: hue-rotate(0deg);
  }
  to {
    filter: hue-rotate(360deg);
  }
}

.title-text{

  color: orange;
  line-height: 1.5;
  text-shadow: 1px 1px 5px #666;
  text-align: center;
  font-weight: 600;
  animation: hue-rotate 10s infinite;
  font-family: 'Gill Sans', sans-serif;
}
</style>